package com.shiguo365.market.display.fragment;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.recker.flybanner.FlyBanner;
import com.shiguo365.market.R;
import com.shiguo365.market.display.activity.DetailActivity;
import com.shiguo365.market.display.activity.MarketPriceActivity;
import com.shiguo365.market.display.activity.ProductListActivity;
import com.shiguo365.market.display.activity.WebViewActivity;
import com.shiguo365.market.display.adapter.ProductAdapter;
import com.shiguo365.market.bean.Product;
import com.shiguo365.market.display.view.IIndexView;
import com.shiguo365.market.presenter.contract.IIndexPresenter;
import com.shiguo365.market.presenter.implement.IndexPresenter;
import com.shiguo365.market.utils.HandlerUtils;
import com.yalantis.phoenix.PullToRefreshView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by caomenglong on 16/7/4.
 */
public class IndexFragment extends Fragment implements IIndexView {

    private static final String TAG = "IndexFragment";


    private List<Product> productList1=new ArrayList<Product>();
    private List<Product> productList2=new ArrayList<Product>();
    private List<Product> productList3=new ArrayList<Product>();

    private View mView;

    PullToRefreshView mPullToRefreshView;
    IIndexPresenter iIndexPresenter =null;

    @BindView(R.id.listView1) ListView listView1;
    @BindView(R.id.listView2) ListView listView2;
    @BindView(R.id.listView3) ListView listView3;
    @BindView(R.id.banner) FlyBanner mBannerNet;

    private List<JSONObject> sliderList = new ArrayList<>();
    private List<String> imgesUrl = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater,container,savedInstanceState);

        View view = inflater.inflate(R.layout.fragment_index, container, false);
        ButterKnife.bind(this,view);

        //initNetBanner(view); //加载轮播图
        mView=view;

        iIndexPresenter = new IndexPresenter(this,this);
        iIndexPresenter.getIndexProList();//初始化商品数据
        iIndexPresenter.getSlideBoxDataList(); //初始化轮播图数据


        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Product product = productList1.get(i);
                //toast(product.getName()+Integer.toString(product.getId()));
                Intent intent =new Intent(getActivity(), DetailActivity.class);
                String productId = String.valueOf(product.getId());
                intent.putExtra("productId",productId);
                startActivity(intent);
            }
        });
        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Product product = productList2.get(i);
                //toast(product.getName()+Integer.toString(product.getId()));
                Intent intent =new Intent(getActivity(), DetailActivity.class);
                String productId = String.valueOf(product.getId());
                intent.putExtra("productId",productId);
                startActivity(intent);
            }
        });
        listView3.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Product product = productList3.get(i);
                //toast(product.getName()+Integer.toString(product.getId()));
                Intent intent =new Intent(getActivity(), DetailActivity.class);
                String productId = String.valueOf(product.getId());
                intent.putExtra("productId",productId);
                startActivity(intent);
            }
        });



        //*********刷新功能



        mPullToRefreshView = (PullToRefreshView) view.findViewById(R.id.pull_to_refresh);
        mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPullToRefreshView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //toast("刷新完成！");
                        iIndexPresenter.getIndexProList();//刷新商品数据
                        iIndexPresenter.getSlideBoxDataList(); //初始化轮播图数据

                    }
                }, 2000);
            }
        });

        return view;
    }


    /***
     * 界面跳转
     */
    //更多世果爆款
    @OnClick(R.id.btn_moreproduct_sgbk)
    protected void  btnSgbk(){
        goToProductActivity("世果爆款","CHEAP");

    }
    //更多世果新品
    @OnClick(R.id.btn_moreproduct_sgxp)
    protected void  btnSgxp(){
        goToProductActivity("世果新品","XP");

    }
    //更多世果特价
    @OnClick(R.id.btn_moreproduct_sgtj)
    protected void  btnSgtj(){
        goToProductActivity("世果特价","TJ");
    }

    //全部商品列表
    @OnClick(R.id.tv_allproduct)
    protected void  btnall(){
        goToProductActivity("全部商品","");
    }
    //最新到货
    @OnClick(R.id.tv_zxdh)
    protected void  tv_zxdh(){
        goToProductActivity("世果新品","XP");

    }
    //世果爆款
    @OnClick(R.id.tv_sgbk)
    protected void  tv_sgbk(){
        goToProductActivity("世果爆款","CHEAP");

    }


    private void goToProductActivity(String tagName,String tagCode){
        Intent intent = new Intent(this.getActivity(), ProductListActivity.class);
        intent.putExtra("tagName",tagName);
        intent.putExtra("tagCode",tagCode);
        startActivity(intent);
    }



    /**
     * 加载网页图片
     */
    private void initNetBanner(View view) {
        mBannerNet = (FlyBanner) view.findViewById(R.id.banner);

        String[] mImagesUrl = {
                "http://7xj380.com1.z0.glb.clouddn.com/2016-07-03_5778d0726ac00.png",
                "http://7xj380.com1.z0.glb.clouddn.com/2016-07-03_5778d43571e6e.png",
                "http://7xj380.com1.z0.glb.clouddn.com/2016-07-03_5778e8177ea01.png",
                "http://7xj380.com1.z0.glb.clouddn.com/2016-06-30_577479528ff61.png"
        };

        List<String> imgesUrl = new ArrayList<>();
        for (int i = 0; i < mImagesUrl.length; i++) {
            imgesUrl.add(mImagesUrl[i]);
        }
        mBannerNet.setImagesUrl(imgesUrl);

        mBannerNet.setOnItemClickListener(new FlyBanner.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                toast("点击了第" + position + "张图片");
            }
        });
    }

    private void toast(String str) {
        Toast.makeText(this.getActivity(), str, Toast.LENGTH_SHORT).show();
    }



    //初始化商品列表模拟
    private void initProduct(){
        Product product = new Product();
        product.setId(1);
        product.setName("海南菠萝蜜");
        product.setContext("海南菠萝蜜的介绍");
        product.setPrice(189.22);
        product.setSpecname("约23斤每箱");
        product.setImgurl("http://7xj380.com1.z0.glb.clouddn.com/2016-05-27_574828de4587e.png");
        productList1.add(product);
        product = new Product();
        product.setId(2);
        product.setName("美国JJ级车厘子");
        product.setContext("美国JJ级车厘子的介绍");
        product.setPrice(500.00);
        product.setSpecname("约15斤每箱");
        product.setImgurl("http://7xj380.com1.z0.glb.clouddn.com/2016-07-01_57763965ecce4.jpg");
        productList1.add(product);
        product = new Product();
        product.setId(3);
        product.setName("新疆金蜜哈密瓜");
        product.setContext("新疆金蜜哈密瓜的介绍");
        product.setPrice(100.00);
        product.setSpecname("约40斤每箱");
        product.setImgurl("http://7xj380.com1.z0.glb.clouddn.com/2016-07-05_577b2b5822232.jpg");
        productList1.add(product);
        product = new Product();
        product.setId(4);
        product.setName("智利有籽红提");
        product.setContext("智利有籽红提的介绍");
        product.setPrice(100.00);
        product.setSpecname("约20斤每箱");
        product.setImgurl("http://7xj380.com1.z0.glb.clouddn.com/2016-05-29_574ab09d4c8f1.png");
        productList1.add(product);


    }


    /**
     * 动态设置ListView的高度
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if(listView == null) return;
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }


    private OtherItemAction mMarketPriceAction = new OtherItemAction(MarketPriceActivity.class);


    private class OtherItemAction implements Runnable {

        private Class gotoClz;

        protected OtherItemAction(Class gotoClz) {
            this.gotoClz = gotoClz;
        }

        @Override
        public void run() {
            startActivity(new Intent(getActivity(), gotoClz));

        }

        public void startDelayed() {
            HandlerUtils.postDelayed(this, 100);
        }

    }

    @OnClick(R.id.tv_market_price)
    public void onTvMarketPriceOnClick(View view){
        mMarketPriceAction.startDelayed();
    }




    //从网络中返回数据
    @Override
    public void onGetIndexProListOk(@NonNull JSONObject result) {
        //Log.d(TAG,result.toJSONString());
        productList1.clear();
        productList2.clear();
        productList3.clear();


        JSONArray array1 = result.getJSONArray("CHEAP"); //TJ CHEAP
        for (int i = 0; i < array1.size(); i++) {
            JSONObject jo = (JSONObject) array1.get(i);
            System.out.println("返回一个JSON对象：" + jo);
            Product product = new Product();
            product.setId(jo.getInteger("id"));
            product.setName(jo.getString("name"));
            product.setContext(jo.getString("intro"));
            product.setPrice(jo.getDouble("price"));
            product.setSpecname(jo.getString("quantity"));
            product.setImgurl(jo.getString("main_pic"));
            productList1.add(product);
        }


        JSONArray array2 = result.getJSONArray("XP"); //TJ CHEAP
        for (int i = 0; i < array2.size(); i++) {
            JSONObject jo = (JSONObject) array2.get(i);
            System.out.println("返回一个JSON对象：" + jo);
            Product product = new Product();
            product.setId(jo.getInteger("id"));
            product.setName(jo.getString("name"));
            product.setContext(jo.getString("intro"));
            product.setPrice(jo.getDouble("price"));
            product.setSpecname(jo.getString("quantity"));
            product.setImgurl(jo.getString("main_pic"));
            productList2.add(product);
        }


        JSONArray array3 = result.getJSONArray("TJ"); //TJ CHEAP
        for (int i = 0; i < array3.size(); i++) {
            JSONObject jo = (JSONObject) array3.get(i);
            System.out.println("返回一个JSON对象：" + jo);
            Product product = new Product();
            product.setId(jo.getInteger("id"));
            product.setName(jo.getString("name"));
            product.setContext(jo.getString("intro"));
            product.setPrice(jo.getDouble("price"));
            product.setSpecname(jo.getString("quantity"));
            product.setImgurl(jo.getString("main_pic"));
            productList3.add(product);
        }


        ProductAdapter adapter1 = new ProductAdapter(this.getActivity(),R.layout.item_product,productList1);
        ProductAdapter adapter2 = new ProductAdapter(this.getActivity(),R.layout.item_product,productList2);
        ProductAdapter adapter3 = new ProductAdapter(this.getActivity(),R.layout.item_product,productList3);

        listView1.setAdapter(adapter1);
        setListViewHeightBasedOnChildren(listView1);

        listView2.setAdapter(adapter2);
        setListViewHeightBasedOnChildren(listView2);

        listView3.setAdapter(adapter3);
        setListViewHeightBasedOnChildren(listView3);


    }

    @Override
    public void onGetIndexProListFinish() {
        mPullToRefreshView.setRefreshing(false);
    }

    @Override
    public void onGetHomeSlider(@NonNull List<JSONObject> jsonObjectList) {

        sliderList.clear();
        imgesUrl.clear();

        for (int i = 0; i < jsonObjectList.size(); i++) {
            JSONObject jo =  jsonObjectList.get(i);
            sliderList.add(jo);
            imgesUrl.add(jo.getString("fileurl"));
        }

        Log.d(TAG,jsonObjectList.toString());

        mBannerNet.setImagesUrl(imgesUrl);

        mBannerNet.setOnItemClickListener(new FlyBanner.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //toast("点击了第" + position + "张图片");
                String urlstr=sliderList.get(position).getString("urlstr");
                Intent intent =new Intent(mView.getContext(),WebViewActivity.class);
                intent.putExtra("url",urlstr);
                startActivity(intent);

            }
        });

    }

    @Override
    public void onGetHomeSliderFinish() {

    }
}
